package com.ruoyi.plus.utils;

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * p6spy打印日志输出格式修改
 * 1.只打印最终执行的sql.
 * 2.sql换到下一行
 * 3.结尾处增加分号,以标示sql结尾
 *
 * @author likun
 * @since 2020年1月30日
 */
public class P6SpyLogger implements MessageFormattingStrategy {
    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    private List<String> ignoreStrings = Arrays.asList("DUAL", "QRTZ_");

    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        final String finalSql = sql.trim().toUpperCase();

        boolean ignore = ignoreStrings.stream().anyMatch((e) -> finalSql.indexOf(e.trim().toUpperCase()) > 0);
        if (ignore) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        return buffer.append("/* ").append(format.format(new Date())).append(" | took ")
                .append(elapsed).append("ms | ").append(category)
                .append(" | connection ").append(connectionId).append(" */ \n ")
                .append(sql).append(";\n").toString();

    }
}
